package com.chookss.home.document;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.FolderEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.knowledge.BuildDirectoryActivity;
import com.chookss.home.knowledge.adaper.FolderAdapter;
import com.chookss.home.knowledge.adaper.JustOpenListAdapter;
import com.chookss.mine.personal.upload.UploadFileService;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DocunmentTypeDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareChoiceDialogListener;
import com.chookss.view.UploadBottomDialog;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class DocumentBaseDirectorySecondActivity extends BaseAct {

    public Context mContext;
    @BindView(R.id.topFlowLayout)
    RecyclerView titleRcv;
    @BindView(R.id.llLine2)
    View llLine2;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.folderRcv)
    RecyclerView folderRcv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.tvFolderName)
    TextView tvFolderName;
    @BindView(R.id.ivFolderArrow)
    ImageView ivFolderArrow;
    @BindView(R.id.llFolderArrow)
    LinearLayout llFolderArrow;
    @BindView(R.id.llFolder)
    LinearLayout llFolder;
    @BindView(R.id.tvFolderTopName)
    TextView tvFolderTopName;
    @BindView(R.id.llFolderTop)
    LinearLayout llFolderTop;
    @BindView(R.id.llFolderAll)
    LinearLayout llFolderAll;
    @BindView(R.id.tvFileName)
    TextView tvFileName;
    @BindView(R.id.ivFileArrow)
    ImageView ivFileArrow;
    @BindView(R.id.llFileArrow)
    LinearLayout llFileArrow;
    @BindView(R.id.llFile)
    LinearLayout llFile;
    @BindView(R.id.tvFileTopName)
    TextView tvFileTopName;
    @BindView(R.id.llFileTop)
    LinearLayout llFileTop;
    @BindView(R.id.llFileAll)
    LinearLayout llFileAll;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvFileArrow)
    TextView tvFileArrow;
    @BindView(R.id.tvFolderArrow)
    TextView tvFolderArrow;
    @BindView(R.id.spaceView)
    View spaceView;
    @BindView(R.id.llAdd)
    LinearLayout llAdd;

    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    //文件夹
    private List<FolderEntity> folderList = new ArrayList<>();
    private FolderAdapter folderAdapter;
    //文件
    private JustOpenListAdapter fileListAdapter;
    private List<FileEntity.ListBean> fileList = new ArrayList<>();
    //目录
    private TitleAdapter titleAdapter;
    private ArrayList<String> nameList = new ArrayList<>();//组织排列
    private String TAG = "DocumentBaseNewSecondActivity_DownloadFile";
    private int level = 1;//默认层级
    private String parentCode, folderNum;//上层级传下来的

    private boolean folderOpen = false, fileOpen = false;//默认都是关闭状态
    private String folderName = "", fileName = "";
    private List<Map<String, String>> dialogList = new ArrayList<>();
    private DocunmentTypeDialog bottomListsDialog = null;
    private int orderType = 0;//0--时间 1--名称 2--类别 3--大小
    private String orderMode = "desc";//升序 asc 降序 desc
    private KnowledgeEntity levelOne;//一级目录数据
    private static final int REQUEST_CODE_CHOOSE = 23;
    private String catalogType;//（0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_knowledge_second);
        ButterKnife.bind(this);
        mContext = this;
        initState();
    }

    @Override
    public void initData() {
//        ivSort.setVisibility(View.VISIBLE);
        level = getIntent().getIntExtra("level", 0);
        catalogType = getIntent().getStringExtra("catalogType");
        levelOne = (KnowledgeEntity) getIntent().getSerializableExtra("levelOne");
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
        }
        if (nameList.size() > 1) {
            tvTitle.setText(nameList.get(nameList.size() - 1));
            titleAdapter = new TitleAdapter(R.layout.item_folder_name_list, this, nameList);
            LinearLayoutManager lm = new LinearLayoutManager(this);
            lm.setOrientation(LinearLayoutManager.HORIZONTAL);
            titleRcv.setLayoutManager(lm);
            titleRcv.setAdapter(titleAdapter);
            titleRcv.setVisibility(View.VISIBLE);
            llLine2.setVisibility(View.VISIBLE);
        } else {
            if (nameList.size() == 1) {
                tvTitle.setText(nameList.get(0));
            } else {
                tvTitle.setText("目录");
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("name", "时间排序");
        map.put("type", "1");
        dialogList.add(map);
        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "名称排序");
        map2.put("type", "1");
        dialogList.add(map2);
        Map<String, String> map3 = new HashMap<>();
        map3.put("name", "文件大小排序");
        map3.put("type", "1");
        dialogList.add(map3);
//        tvRight.setText("时间排序");
        bottomListsDialog = new DocunmentTypeDialog(mContext, dialogList, new ShareChoiceDialogListener() {
            @Override
            public void onClick(int position) {
//                tvRight.setText(dialogList.get(position / 2).get("name"));
                if (position == 0) {
                    orderType = 0;
                    orderMode = "asc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_up_14);
                } else if (position == 1) {
                    orderType = 0;
                    orderMode = "desc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_down_14);
                } else if (position == 2) {
                    orderType = 1;
                    orderMode = "asc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_up_14);
                } else if (position == 3) {
                    orderType = 1;
                    orderMode = "desc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_down_14);
                } else if (position == 4) {
                    orderType = 3;
                    orderMode = "asc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_up_14);
                } else if (position == 5) {
                    orderType = 3;
                    orderMode = "desc";
//                    ivSort.setBackgroundResource(R.drawable.arrow_down_14);
                }
                srlView.autoRefresh();
            }
        });
        parentCode = getIntent().getStringExtra("parentCode");
        folderNum = getIntent().getStringExtra("folderNum");
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getFileList();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getCatalogData();
                //定时器 倒计时
                Observable.timer(200, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) {
                                getFileList();
                            }
                        });
            }
        });
        //文件夹
        folderRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        folderAdapter = new FolderAdapter(R.layout.item_knowledge_folder, this, folderList, nameList, level, "", catalogType, 2, levelOne, "");
        folderRcv.setAdapter(folderAdapter);
        //文件
        fileRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fileListAdapter = new JustOpenListAdapter(R.layout.item_knowledge_look, this, fileList, TAG + level);
        ((SimpleItemAnimator) fileRcv.getItemAnimator()).setSupportsChangeAnimations(false);
        fileRcv.setAdapter(fileListAdapter);
        srlView.autoRefresh();
        registerBoradcastReceiver();
        //检查权限
        checkUpdate();
    }

    private void checkUpdate() {
        if ("3".equals(parentCode) || "2".equals(parentCode) || "3001".equals(parentCode)) {
            // 个人文件和我的部门的第二级不能添加   我的上传也不能传
            return;
        }
        Map<String, String> map = new HashMap<>();
//        （0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）
        map.put("catalogCode", parentCode);
        map.put("catalogType", catalogType);
        KLog.i("------" + catalogType + "==" + parentCode + "--" + level);
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.checkUpdate, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        folderAdapter.setPermissions(true);
                        llAdd.setVisibility(View.VISIBLE);
                    } else {
                        folderAdapter.setPermissions(false);
                        llAdd.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    private void getCatalogData() {
        Map<String, String> map = new HashMap<>();
        map.put("parentCode", parentCode);
        map.put("catalogType", "3");
        map.put("orderType", orderType + "");
        if (!Utils.isNull(orderMode)) {
            map.put("orderMode", orderMode);
        }
        //        catalogType 目录类型 1-小视频，2长视频 3资料库
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<FolderEntity>>>() {
        }.getType(), null, Urls.selectAPPCatalogTreeGlobal, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<FolderEntity>>() {
            @Override
            public void onSuccess(List<FolderEntity> data) {
                loadEnd();
                folderList.clear();
                folderAdapter.notifyDataSetChanged();
                if (data != null && data.size() > 0) {
                    folderList.addAll(data);
                    folderAdapter.notifyDataSetChanged();
//                    for (int i = 0; i < data.size(); i++) {
//                        if (i == 0) {
//                            folderName = folderName + data.get(i).getName();
//                        } else {
//                            folderName = folderName + "," + data.get(i).getName();
//                        }
//                    }
//                    tvFolderTopName.setText(folderName);
                }
                llFolderTop.setVisibility(View.GONE);
                folderOpen = false;
                tvFolderArrow.setVisibility(View.INVISIBLE);
                ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (folderList.size() == 0) {
                    folderRcv.setVisibility(View.GONE);
                    llFolderAll.setVisibility(View.GONE);
                    spaceView.setVisibility(View.GONE);
                } else {
                    folderRcv.setVisibility(View.VISIBLE);
                    llFolderAll.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                    if (fileList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                }
                if (folderList.size() > 0) {
                    tvFolderTopName.setText("共" + folderList.size() + "个文件夹");
                    tvFolderName.setText("文件夹");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getFileList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("resourceType", "1");
        map.put("catalogType", "3");
        map.put("parentCode", parentCode);
        map.put("orderType", orderType + "");
        if (!Utils.isNull(orderMode)) {
            map.put("orderMode", orderMode);
        }
        //        fileFlag 0不包含当前目录文件 1包含
        map.put("fileFlag", "0");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<FileEntity>>() {
        }.getType(), null, Urls.getFileByParentCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<FileEntity>() {
            @Override
            public void onSuccess(FileEntity data) {
                loadEnd();
                if (currentPage == 1) {
                    fileList.clear();
                    fileListAdapter.notifyDataSetChanged();
                }
                llFileTop.setVisibility(View.GONE);
                fileOpen = false;
                tvFileArrow.setVisibility(View.INVISIBLE);
                ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (data != null && data.getList().size() > 0) {
                    fileList.addAll(data.getList());
                    fileListAdapter.notifyDataSetChanged();
                    fileRcv.setVisibility(View.VISIBLE);
                    llFileAll.setVisibility(View.VISIBLE);
                    if (folderList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                    llNone.setVisibility(View.GONE);
//                    if (currentPage == 1) {
//                        for (int i = 0; i < data.getList().size(); i++) {
//                            if (i == 0) {
//                                fileName = fileName + data.getList().get(i).getResourceName();
//                            } else {
//                                fileName = fileName + "," + data.getList().get(i).getResourceName();
//                            }
//                            tvFileTopName.setText(fileName);
//                        }
//                    }
                } else {
                    isEnd = true;
                    if (fileList.size() == 0) {
                        spaceView.setVisibility(View.GONE);
                        fileRcv.setVisibility(View.GONE);
                        llFileAll.setVisibility(View.GONE);
                        if (folderList.size() == 0) {
                            llNone.setVisibility(View.VISIBLE);
                        } else {
                            llNone.setVisibility(View.GONE);
                        }
                    } else {
                        if (folderList.size() > 0) {
                            spaceView.setVisibility(View.VISIBLE);
                        } else {
                            spaceView.setVisibility(View.GONE);
                        }
                        fileRcv.setVisibility(View.VISIBLE);
                        llFileAll.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    }
                }
                if (fileList.size() > 0) {
                    tvFileTopName.setText("共" + data.getTotalNum() + "个文件");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class TitleAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Activity context;

        public TitleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvItemTitle = helper.getView(R.id.tvTitle);
            ImageView ivArrow = helper.getView(R.id.ivArrow);
            tvItemTitle.setText(entity);
            if (helper.getItemPosition() > 0) {
                ivArrow.setVisibility(View.VISIBLE);
            } else {
                ivArrow.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == nameList.size() - 1) {
                tvItemTitle.setTextColor(Color.parseColor("#333333"));
            } else {
                tvItemTitle.setTextColor(Color.parseColor("#8a8a8a"));
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }

                    HashMap<String, String> map = new HashMap<>();
                    if (helper.getItemPosition() == 0) {
                        if (levelOne != null) {
                            Intent intent = new Intent(context, DocumentBaseDirectorySecondActivity.class);
                            intent.putExtra("parentCode", levelOne.getCode());
                            intent.putExtra("folderNum", levelOne.getFolderNum());
                            intent.putExtra("levelOne", levelOne);
                            intent.putExtra("level", 1);
                            ArrayList<String> nameList = new ArrayList<>();//组织排列
                            nameList.add(levelOne.getName());
                            intent.putStringArrayListExtra("nameList", nameList);
                            startActivity(intent);
                        }
                        map.put("DocumentBaseNewSecond", "0");
                        EventBus.getDefault().post(new MyEvent(map));
                    } else {
                        map.put("DocumentBaseNewSecond", (helper.getItemPosition() + 1) + "");
                        EventBus.getDefault().post(new MyEvent(map));
                    }

                }
            });
        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh();
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("DocumentBaseNewSecond")) {
                int oldLevel = Utils.changeNumber(map.get("DocumentBaseNewSecond"));
                if (level > oldLevel) {
                    finish();
                }
            } else if (map.containsKey("DocumentPreview_error")) {
                for (int i = 0; i < fileList.size(); i++) {
                    if ("1".equals(fileList.get(i).getResourceType())) {
                        if (fileList.get(i).getResourceId().equals(map.get("DocumentPreview_error"))) {
                            fileList.get(i).setError(true);
                        }
                    }

                }

            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("RefreshDirectory")) {
                    srlView.autoRefresh();
                }
            }
        }
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < fileList.size(); i++) {
                    if ("1".equals(fileList.get(i).getResourceType())) {
                        if (fileList.get(i).getResourceId().equals(recevierDataCode)) {
                            if (!fileList.get(i).isOpen()) {
                                if (encryptStatus) {
                                    fileList.get(i).setOpen(true);
                                }
                                dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }

                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);

            }
        } else {
            if (percent > 0 && percent < 100) {
                if (fileListAdapter != null) {
                    fileList.get(position).setProgress(percent);
                    fileListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (fileListAdapter != null) {
                    fileList.get(position).setProgress(100);
                    fileListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(DocumentBaseDirectorySecondActivity.this, fileUrl, fileName, recevierDataCode, TAG + level);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(TAG + level);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            FilePicker
                                    .from(DocumentBaseDirectorySecondActivity.this)
                                    .chooseForMimeType()
                                    .setMaxCount(9)
                                    .setFileTypes("pdf", "doc", "ppt", "xls")
                                    .requestCode(REQUEST_CODE_CHOOSE)
                                    .start();
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(mContext, denied, quick);
                    }
                });
    }

    @OnClick({R.id.title_back, R.id.llChoose, R.id.llAdd, R.id.llFileArrow, R.id.llFolderArrow, R.id.llFolderTop, R.id.llFileTop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.llAdd:
                String dialogType = "";
                if (level == 1) {
                    //限制自定义下第一层只能新建文件夹，不能新增
                    dialogType = "99";
                } else {
                    dialogType = "3";
                }
                new UploadBottomDialog(mContext, 1, dialogType, new HomeBottomDialogListener() {
                    @Override
                    public void onListItemClick(int position) {
                        if (position == 0) {
//                      （0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）
                            Intent intent = new Intent(mContext, BuildDirectoryActivity.class);
                            intent.putExtra("catalogType", catalogType);
                            intent.putExtra("parentCode", parentCode);
                            intent.putStringArrayListExtra("nameList", nameList);
                            mContext.startActivity(intent);
                        } else if (position == 1) {
                            requestCamera();
                        }
                    }
                }).show();
                break;
            case R.id.llChoose:
                if (bottomListsDialog != null) {
                    bottomListsDialog.show();
                }
                break;
            case R.id.llFolderArrow:
            case R.id.llFolderTop:
                if (folderOpen) {
                    folderOpen = false;
                    tvFolderArrow.setVisibility(View.INVISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFolderTop.setVisibility(View.GONE);
                    folderRcv.setVisibility(View.VISIBLE);
                } else {
                    folderOpen = true;
                    tvFolderArrow.setVisibility(View.VISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFolderTop.setVisibility(View.VISIBLE);
                    folderRcv.setVisibility(View.GONE);
                }
                break;
            case R.id.llFileArrow:
            case R.id.llFileTop:
                if (fileOpen) {
                    fileOpen = false;
                    tvFileArrow.setVisibility(View.INVISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFileTop.setVisibility(View.GONE);
                    fileRcv.setVisibility(View.VISIBLE);
                } else {
                    fileOpen = true;
                    tvFileArrow.setVisibility(View.VISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFileTop.setVisibility(View.VISIBLE);
                    fileRcv.setVisibility(View.GONE);
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                ArrayList< UploadEntity> docList = new ArrayList<>();
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        UploadEntity uploadEntity = new  UploadEntity();
                        UploadEntity.DataBaseBean docunmentEntity= new UploadEntity.DataBaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setParentCode(parentCode);
                        docunmentEntity.setParentName(nameList.get(nameList.size() - 1));
                        docunmentEntity.setDataPath(nameList.get(nameList.size() - 1));
                        docunmentEntity.setLocalDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setFileType(FileUtils.getExtensionType(essFileList.get(i).getName()).toLowerCase());
                        docunmentEntity.setProvideEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
                        docunmentEntity.setProvideEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
                        docunmentEntity.setUploadTime(Utils.getCurrentTime2());
                        docunmentEntity.setShareFlag("1");
                        docunmentEntity.setOriginal("1");
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        uploadEntity.setDataBase(docunmentEntity);
                        uploadEntity.setUploadStatus(1);
                        uploadEntity.setResourceType("1");
                        uploadEntity.setProvideEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
                        uploadEntity.setUploadTitle(essFileList.get(i).getName());
                        uploadEntity.setUploadTag(Utils.getCurrentTime2()+"-"+i);
                        docList.add(uploadEntity);
                    }
                    Intent intent = new Intent(DocumentBaseDirectorySecondActivity.this, UploadFileService.class);
                    Bundle bundle = new Bundle();
                    //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
                    ArrayList bundlelist = new ArrayList();
                    bundlelist.add(docList);
                    bundle.putParcelableArrayList("data", bundlelist);
                    intent.putExtras(bundle);
                    intent.putExtra("resourceType","1");
                    KLog.i("--------");
                    startService(intent);
                } else {
                    KLog.i("essFileList.size() == 0");
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
    }
}
